﻿#include "SharedMemory.h"
#include "SharedMemoryImpl.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <fcntl.h>
#endif

SharedMemory::SharedMemory(const std::string &key)
{
    m_impl = SharedMemoryImpl::CreateImpl(key);
}

SharedMemory::~SharedMemory()
{
}

bool SharedMemory::Create(size_t size)
{
    return m_impl->Create(size);
}

bool SharedMemory::Attach(SharedMemory::AccessMode mode)
{
#ifdef _WIN32
    int permissions = (mode == SharedMemory::ReadOnly ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE);
#else
    int permissions = (mode == SharedMemory::ReadOnly ? O_RDONLY : O_RDWR);
#endif
    return m_impl->Attach(permissions);
}

bool SharedMemory::Detach()
{
    return m_impl->Detach();
}

bool SharedMemory::IsAttached() const
{
    return m_impl->IsAttached();
}

int SharedMemory::Write(unsigned char *data, size_t size)
{
    return m_impl->Write(data, size);
}

int SharedMemory::Read(unsigned char *buf, size_t size)
{
    return m_impl->Read(buf, size);
}

unsigned char *SharedMemory::Data()
{
    return (unsigned char *)m_impl->GetData();
}

int SharedMemory::DataLen()
{
    return m_impl->GetDataSize();
}

void SharedMemory::Lock()
{
    m_impl->Lock();
}

void SharedMemory::Unlock()
{
    m_impl->Unlock();
}
